package com.tsl.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsl.reggie.common.R;
import com.tsl.reggie.domain.po.Category;
import com.tsl.reggie.service.ICategoryService;
import com.tsl.reggie.service.impl.CategoryServiceImpl;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 菜品及套餐分类 前端控制器
 * </p>
 *
 * @author 唐书亮
 * @since 2024-01-20
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    ICategoryService categoryService;

    /**
     * @param category
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("添加成功");
    }

    //分页查询
    @GetMapping("page")
    public R<Page> selectPage(Integer page, Integer pageSize) {
        Page pageInit = new Page(page, pageSize);
        //条件构造
        pageInit.addOrder(OrderItem.asc("sort"));
        Page page1 = categoryService.page(pageInit);
        return R.success(page1);
    }

    //删除分类
    @DeleteMapping
    public R<String> delete(Long ids) {
        Boolean isRemove = categoryService.remove(ids);
        if (isRemove) {
            return R.success("删除成功");
        }
        return R.error("未知错误");
    }

    //修改分类
    @PutMapping
    public R<String> updateInfo(@RequestBody Category category) {
        boolean update = categoryService.updateById(category);
        if (update) {
            return R.success("修改成功");
        }
        return R.error("修改失败");
    }
    //查询菜品分类
    @GetMapping("list")
    public R<List<Category>> getCategoryById(Category category){
        //构造条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        //添加排序条件
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);

        return R.success(list);
    }

}
